<!--  -->
<template>
  <div class="infoview">
    <div>
      <div>
        <el-row>
          <span>范围：</span>
          <el-radio v-model="radio" label="1"><font color="white">全重庆</font></el-radio>
          <el-radio v-model="radio" label="2"><font color="white">视域范围</font></el-radio>
          <el-radio v-model="radio" label="3"><font color="white">框选范围</font></el-radio>
        </el-row>
      </div>
      <div class="queryByDraw" style="margin-top: 10px; text-align: center" v-show="radio === '3'">
        <el-row>
          <el-button type="primary" size="small" @click="drawRectangle">矩形范围</el-button>
          <el-button type="primary" size="small" @click="drawCircle">圆形范围</el-button>
          <el-button type="primary" size="small" @click="drawPolygon">多边形范围</el-button>
        </el-row>
      </div>
      <div style="margin-top: 10px" class="keywordRow">
        <el-row>
          <span>关键字：</span>
          <el-input placeholder="查询名称或地址" prefix-icon="el-icon-search" v-model="keyword" id="queryText"> </el-input>
        </el-row>
      </div>
    </div>

    <div style="margin-top: 10px; margin-bottom: 10px; text-align: center">
      <el-row>
        <el-button type="primary" size="small" @click="query">查询</el-button>
        <el-button type="primary" size="small" @click="removeAll(false, true)">清除</el-button>
      </el-row>
    </div>

    <div class="resultView" v-show="hasResult" v-loading="isLoading">
      <el-table :data="tableData" style="width: 350px" height="250" @row-click="handleRowClick">
        <el-table-column fixed prop="name" label="名称" width="100"> </el-table-column>
        <el-table-column prop="type" label="类型" width="100"> </el-table-column>
        <el-table-column prop="address" label="地址" width="150"> </el-table-column>
      </el-table>
      <el-pagination small layout="total,prev,pager,next" style="float: right" @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize" :total="total"> </el-pagination>
    </div>

    <div id="allmap" style="display: none"></div>
  </div>
</template>

<script>
// const eventTarget = new this.mars3d.BaseClass()
// const poiLayer = new this.mars3d.layer.GraphicLayer()
import BMap from 'BMap'
import communityApi from '@/api/community.js'
export default {
  name: 'GeodePoi',
  data() {
    return {
      radio: '1',
      input1: '',
      keyword: '',
      tableData: [],
      hasResult: false,
      isLoading: false,
      resultList: [],
      isFirstQuery: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      houseGraphic: null,
      colors: ['#EC3F23', '#F30170', '#CB39B7', '#6665E6', '#007DED']
    }
  },
  // 生命周期 - 创建完成（访问当前this实例）
  created() {
    this.graphicLayer = new this.mars3d.layer.GraphicLayer()
    this.map.addLayer(this.graphicLayer)
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.queryGaodePOI = new this.mars3d.query.GaodePOI({
      key: [this.ak.gaode] // ae29a37307840c7ae4a785ac905927e0
    })
  },
  beforeDestroy() {
    this.removeAll(false, false)
    this.graphicLayer.remove()
  },
  methods: {
    drawRectangle() {
      this.removeAll(false, true)
      var that = this
      this.graphicLayer.startDraw({
        type: 'rectangle',
        style: {
          color: '#00FF00',
          opacity: 0.3,
          outline: true,
          outlineColor: '#ffffff',
          clampToGround: true
        },
        success: function (graphic) {
          that.drawGraphic = graphic
        }
      })
    },
    drawCircle() {
      this.removeAll(false, true)
      var that = this
      this.graphicLayer.startDraw({
        type: 'circle',
        style: {
          color: '#00FF00',
          opacity: 0.3,
          outline: true,
          outlineColor: '#ffffff',
          clampToGround: true
        },
        success: function (graphic) {
          that.drawGraphic = graphic
        }
      })
    },
    drawPolygon() {
      this.removeAll(false, true)
      var that = this
      this.graphicLayer.startDraw({
        type: 'polygon',
        style: {
          color: '#00FF00',
          opacity: 0.3,
          outline: true,
          outlineColor: '#ffffff',
          clampToGround: true
        },
        success: function (graphic) {
          that.drawGraphic = graphic
        }
      })
    },
    addPoiLayer() {
      if (!this.map.poiLayer) {
        // 创建矢量数据图层
        this.map.poiLayer = new this.mars3d.layer.GraphicLayer()
        this.map.addLayer(this.map.poiLayer)

        this.map.poiLayer.bindPopup(function (event) {
          const item = event.graphic.attr

          let inHtml = '<div class="mars-popup-titile">' + item.name + '</div><div class="mars-popup-content" >'

          const type = String(item.type).trim()
          if (type) {
            inHtml += '<div><label>类别</label>' + type + '</div>'
          }
          const xzqh = String(item.xzqh).trim()
          if (xzqh) {
            inHtml += '<div><label>区域</label>' + xzqh + '</div>'
          }
          const tel = String(item.tel).trim()
          if (tel) {
            inHtml += '<div><label>电话</label>' + tel + '</div>'
          }
          const address = String(item.address).trim()
          if (address) {
            inHtml += '<div><label>地址</label>' + address + '</div>'
          }
          inHtml += '</div>'
          return inHtml
        })
      }
    },
    query() {
      this.hasResult = false
      this.removeAll(true, true) // noClearDraw = true

      this.resultList = []
      switch (this.radio) {
        case '1': {
          // 全重庆
          this.loadData(
            {
              page: 0,
              city: 'chongqing',
              citylimit: true
            },
            this.keyword
          )
          break
        }
        case '2': {
          // 当前视角范围

          const extent = this.map.getExtent()
          this.loadData(
            {
              page: 0,
              polygon: [
                [extent.xmin, extent.ymin],
                [extent.xmax, extent.ymax]
              ],
              limit: true
            },
            this.keyword
          )
          break
        }
        case '3': // 按范围
          if (!this.drawGraphic) {
            this.$message.error('请绘制限定范围！')
            return
          }
          this.loadData(
            {
              page: 0,
              graphic: this.drawGraphic,
              limit: true
            },
            this.keyword
          )
          break
      }
    },
    loadData(queryOptions, text) {
      if (!text) {
        this.$message.warning('请输入 名称 关键字筛选数据！')
        return
      }

      if (this.isFirstQuery) {
        // 第一次查询 先把poiLayer加上去
        this.isFirstQuery = false
        this.addPoiLayer()
      }

      this.hasResult = true
      this.isLoading = true

      var that = this

      this.lastQueryOptions = {
        ...queryOptions,
        count: 10, // count 每页数量
        text: text,
        success: function (res) {
          const data = res.list
          that.total = parseInt(res.allcount)
          // that.resultList = that.resultList.concat(data)

          // that.addGraphics(data)

          that.tableData = data

          that.isLoading = false
        },
        error: function (msg) {
          that.$message.error(msg)
          that.isLoading = false
        }
      }
      this.queryGaodePOI.query(this.lastQueryOptions)
    },
    addGraphics(arr) {
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]

        if (item.type.includes('住宅') || item.type.includes('小区')) {
          this.showArea(item.name, '重庆', item)
        } else {
          const graphic = new this.mars3d.graphic.BillboardEntity({
            position: this.Cesium.Cartesian3.fromDegrees(item.lng, item.lat),
            style: {
              image: 'img/marker/mark3.png',
              scale: 1,
              scaleByDistance: true,
              scaleByDistance_far: 20000,
              scaleByDistance_farValue: 0.5,
              scaleByDistance_near: 1000,
              scaleByDistance_nearValue: 1,
              clampToGround: true, // 贴地
              highlight: { type: 'click', image: 'img/marker/mark1.png' },
              label: {
                text: item.name,
                font: '20px 楷体',
                color: this.Cesium.Color.AZURE,
                outline: true,
                outlineColor: this.Cesium.Color.BLACK,
                outlineWidth: 2,
                horizontalOrigin: this.Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new this.Cesium.Cartesian2(0, -30), // 偏移量
                distanceDisplayCondition: new this.Cesium.DistanceDisplayCondition(0.0, 200000),
                clampToGround: true // 贴地
              }
            },
            attr: item
          })
          this.map.poiLayer.addGraphic(graphic)

          item.graphic = graphic
        }
      }
    },
    handlePageChange(page) {
      this.lastQueryOptions.page = page - 1

      this.loadData(
        {
          ...this.lastQueryOptions
        },
        this.keyword
      )
    },
    handleRowClick(row) {
      // if (row.type.includes('住宅') || row.type.includes('小区')) {
      //   this.showArea(row.name, '重庆', row)
      // } else {
      const graphic = new this.mars3d.graphic.BillboardEntity({
        position: this.Cesium.Cartesian3.fromDegrees(row.lng, row.lat),
        style: {
          image: 'img/marker/mark3.png',
          scale: 1,
          scaleByDistance: true,
          scaleByDistance_far: 20000,
          scaleByDistance_farValue: 0.5,
          scaleByDistance_near: 1000,
          scaleByDistance_nearValue: 1,
          clampToGround: true, // 贴地
          highlight: { type: 'click', image: 'img/marker/mark1.png' },
          label: {
            text: row.name,
            font: '20px 楷体',
            color: this.Cesium.Color.AZURE,
            outline: true,
            outlineColor: this.Cesium.Color.BLACK,
            outlineWidth: 2,
            horizontalOrigin: this.Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: this.Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new this.Cesium.Cartesian2(0, -30), // 偏移量
            distanceDisplayCondition: new this.Cesium.DistanceDisplayCondition(0.0, 200000),
            clampToGround: true // 贴地
          }
        },
        attr: row
      })
      if (graphic) {
        this.map.poiLayer.addGraphic(graphic)
        graphic.openHighlight()
        graphic.flyTo({
          radius: 1000, // 点数据：radius控制视距距离
          scale: 1.5, // 线面数据：scale控制边界的放大比例
          complete: () => {
            graphic.openPopup()
          }
        })
      } else {
        this.$message.warning('没有位置信息')
      }
    },
    removeAll(noClearDraw, isClearPoi) {
      this.houseGraphic = null
      this.hasResult = false
      this.lastQueryOptions = null
      // this.resultList = []
      this.tableData = []
      this.total = 0
      this.currentPage = 0
      if (this.map.poiLayer && isClearPoi) {
        this.map.poiLayer.clear()
      }

      if (!noClearDraw) {
        this.drawGraphic = null

        this.graphicLayer.clear()
      }
    },

    /*
      百度小区边界相关
     */
    queryHouseOutline(hid, callback) {
      var baseURL = 'http://map.baidu.com/?reqflag=pcmap&coord_type=3&from=webmap&qt=ext&ext_ver=new&l=18'
      var url = baseURL + '&uid=' + hid
      callback && (window.queryHouseOutlineCallback = callback)
      $.ajax({
        type: 'get',
        async: false,
        url: url,
        dataType: 'jsonp',
        jsonpCallback: 'queryHouseOutlineCallback',
        success: function (datas) {}
      })
    },
    /**
     * 模糊查询小区信息, 无返回值
     * @param {} house  小区名称
     * @param {} city   所属城市名称
     * @param {} ak     百度地图AK
     * @param {} item   行对象
     * @param {} callback   回调函数，该函数可以接收到请求的返回值
     */
    queryHouse(house, city, ak, item, callback) {
      var baseURL = 'http://api.map.baidu.com/place/v2/search?output=json&scope=2'
      var url = baseURL + '&q=' + house + '&region=' + city + '&ak=' + ak
      callback && (window.queryHouseCallback = callback)
      $.ajax({
        type: 'get',
        async: false,
        url: url,
        dataType: 'jsonp',
        jsonpCallback: 'queryHouseCallback',
        success: function (datas) {}
      })
    },
    /**
     * 墨卡托坐标转百度坐标
     * @param {} coordinate
     * @return {}
     */
    coordinateToPoints(coordinate) {
      var points = []
      if (coordinate) {
        var arr = coordinate.split(';')
        if (arr) {
          for (var i = 0; i < arr.length; i++) {
            var coord = arr[i].split(',')
            if (coord && coord.length === 2) {
              var mctXY = new BMap.Pixel(coord[0], coord[1])
              var map = new BMap.Map('allmap')
              var project = map.getMapType().getProjection()
              var point = project.pointToLngLat(mctXY)
              var bMapPoint = new BMap.Point(point.lng, point.lat)
              var pos = this.mars3d.PointTrans.bd2wgs([bMapPoint.lng, bMapPoint.lat])
              points.push(pos)
            }
          }
        }
      }
      return points
    },
    /**
     * 墨卡托坐标解析
     * @param {} mocator
     * @return {}
     */
    parseGeo(mocator) {
      if (typeof mocator !== 'string') {
        return {}
      }
      var t = mocator.split('|')
      var n = parseInt(t[0])
      var i = t[1]
      var r = t[2]
      var o = r.split(';')
      if (n === 4) {
        for (var a = [], s = 0; s < o.length - 1; s++) {
          o[s].split('-')[0] === '1' && a.push(o[s].split('-')[1])
        }
        o = a
        o.push('')
      }
      var u = []
      switch (n) {
        case 1:
          u.push(o[0])
          break
        case 2:
        case 3:
        case 4:
          for (var ss = 0; ss < o.length - 1; ss++) {
            var l = o[ss]
            if (l.length > 100) {
              l = l.replace(/(-?[1-9]\d*\.\d*|-?0\.\d*[1-9]\d*|-?0?\.0+|0|-?[1-9]\d*),(-?[1-9]\d*\.\d*|-?0\.\d*[1-9]\d*|-?0?\.0+|0|-?[1-9]\d*)(,)/g, '$1,$2;')
              u.push(l)
            } else {
              for (var c = [], d = l.split(','), f = 0; f < d.length; f += 2) {
                var p = d[f]
                var h = d[f + 1]
                c.push(p + ',' + h)
              }
              u.push(c.join(';'))
            }
          }
          break
        default:
          break
      }

      if (u.length <= 1) {
        u = u.toString()
      }

      var result = {
        type: n,
        bound: i,
        points: u
      }
      return result
    },

    showArea(keyword, city, item) {
      var that = this

      this.queryHouse(keyword, city, this.ak.baidu, item, function (data) {
        if (data.message === 'ok') {
          var houses = data.results
          if (houses && houses.length > 0) {
            var house = houses[0]

            communityApi
              .getCommunityByName(house.name, house.area)
              .then((response) => {
                if (response.code === 200) {
                  // 查询到了
                  that.$set(house, 'ke_info', response.data)
                }
              })
              .catch((e) => console.log(e))

            that.queryHouseOutline(house.uid, function (houseOutline) {
              var geo = houseOutline.content.geo
              if (!geo) {
                var location = house.location

                const graphic = new that.mars3d.graphic.BillboardEntity({
                  position: [location.lng, location.lat],
                  style: {
                    image: 'img/marker/mark3.png',
                    scale: 1,
                    horizontalOrigin: that.Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: that.Cesium.VerticalOrigin.BOTTOM,
                    scaleByDistance: new that.Cesium.NearFarScalar(10000, 1.0, 500000, 0.1),
                    label: {
                      text: house.name,
                      font_size: 18,
                      color: that.getColorText(house),
                      pixelOffsetY: -40,
                      distanceDisplayCondition: true,
                      distanceDisplayCondition_far: 500000,
                      distanceDisplayCondition_near: 0
                    }
                  },
                  attr: house.detail_info
                })

                var innerHtml = ''
                if (house.ke_info == null) {
                  // 贝壳找房中没有查询到信息
                  innerHtml = `<table style="width:280px;">
                <tr><th scope="col" colspan="4"  style="text-ke_infoalign:center;font-size:15px;"房屋信息</th></tr>
                <tr><td >名称：</td><td >${house.name} </td></tr>
                <tr><td >类型：</td><td >${house.detail_info.tag} </td></tr>
                </table>`
                } else {
                  innerHtml = `<table style="width:280px;">
                <tr><th scope="col" colspan="4"  style="text-ke_infoalign:center;font-size:15px;"房屋信息</th></tr>
                <tr><td >名称：</td><td >${house.name} </td></tr>
                <tr><td >类型：</td><td >${house.detail_info.tag} </td></tr>
                <tr><td >地址：</td><td >${house.ke_info.comAdd} </td></tr>
                <tr><td >均价：</td><td >${house.ke_info.comPrice + house.ke_info.comPriceUnit} </td></tr>
                <tr><td >建筑类型：</td><td >${house.ke_info.buildingType} </td></tr>
                <tr><td >物业公司：</td><td >${house.ke_info.propertyCompany} </td></tr>
                <tr><td >物业费用：</td><td >${house.ke_info.propertyFee} </td></tr>
                <tr><td >开发商：</td><td >${house.ke_info.developers} </td></tr>
                <tr><td >楼栋总数：</td><td >${house.ke_info.buildingNumber}栋 </td></tr>
                <tr><td >房屋总数：</td><td >${house.ke_info.houseNumber}户 </td></tr>
                >
              </table>`
                }

                graphic.bindPopup(innerHtml).openPopup()

                that.poiLayer.addGraphic(graphic)
                graphic.openHighlight()
                graphic.flyTo({
                  radius: 1000, // 点数据：radius控制视距距离
                  scale: 1.5, // 线面数据：scale控制边界的放大比例
                  complete: () => {
                    graphic.openPopup()
                  }
                })
              } else {
                var geoObj = that.parseGeo(geo)

                // 边界点
                var points = that.coordinateToPoints(geoObj.points)

                var colorText = that.getColorText(house)

                const primitive = new that.mars3d.graphic.PolygonPrimitive({
                  positions: points,
                  style: {
                    color: colorText.color,
                    opacity: 0.4,
                    // clampToGround: true,
                    // classificationType: Cesium.ClassificationType.BOTH,

                    // 高亮时的样式（默认为鼠标移入，也可以指定type:'click'单击高亮），构造后也可以openHighlight、closeHighlight方法来手动调用
                    highlight: {
                      // type: mars3d.EventType.click,
                      opacity: 0.8
                    }
                  }
                })

                var innerHtml = ''

                if (house.ke_info == null) {
                  // 贝壳找房中每查询到信息
                  innerHtml = `<table style="width:280px;">
                <tr><th scope="col" colspan="4"  style="text-ke_infoalign:center;font-size:15px;"房屋信息</th></tr>
                <tr><td >名称：</td><td >${house.name} </td></tr>
                <tr><td >类型：</td><td >${house.detail_info.tag} </td></tr>
                </table>`
                } else {
                  innerHtml = `<table style="width:280px;">
                <tr><th scope="col" colspan="4"  style="text-ke_infoalign:center;font-size:15px;"房屋信息</th></tr>
                <tr><td >名称：</td><td >${house.name} </td></tr>
                <tr><td >类型：</td><td >${house.detail_info.tag} </td></tr>
                <tr><td >地址：</td><td >${house.ke_info.comAdd} </td></tr>
                <tr><td >均价：</td><td >${house.ke_info.comPrice + house.ke_info.comPriceUnit} </td></tr>
                <tr><td >建筑类型：</td><td >${house.ke_info.buildingType} </td></tr>
                <tr><td >物业公司：</td><td >${house.ke_info.propertyCompany} </td></tr>
                <tr><td >物业费用：</td><td >${house.ke_info.propertyFee} </td></tr>
                <tr><td >开发商：</td><td >${house.ke_info.developers} </td></tr>
                <tr><td >楼栋总数：</td><td >${house.ke_info.buildingNumber}栋 </td></tr>
                <tr><td >房屋总数：</td><td >${house.ke_info.houseNumber}户 </td></tr>

              </table>`
                }

                primitive.bindPopup(innerHtml).openPopup()

                that.poiLayer.addGraphic(primitive)

                primitive.flyTo({
                  radius: 1000, // 点数据：radius控制视距距离
                  scale: 1.5, // 线面数据：scale控制边界的放大比例
                  complete: () => {
                    primitive.openPopup()
                  }
                })
              }
            })
          }
        }
      })
    },
    getColorText(row) {
      let colorText = '#ffffff'
      if (row.ke_info != null) {
        const price = row.ke_info.comPrice
        if (price > 15000) {
          colorText = this.colors[0]
        } else if (price > 10000) {
          colorText = this.colors[1]
        } else if (price > 8000) {
          colorText = this.colors[2]
        } else if (price > 5000) {
          colorText = this.colors[3]
        } else {
          colorText = this.colors[4]
        }
      }

      return {
        color: colorText
      }
    }
  }
}
</script>
<style scoped>
/* @import url(); 引入css类 */
/**infoview浮动面板*/
.infoview {
  position: absolute;
  top: 70px;
  left: 20px;
  padding: 10px 15px;
  border-radius: 4px;
  border: 1px solid rgba(128, 128, 128, 0.5);
  color: #ffffff;
  background: rgba(0, 0, 0, 0.5);
  /* box-shadow: 0 3px 14px rgba(128, 128, 128, 0.5); */
  z-index: 19870100;
}
.infoview-right {
  left: auto;
  right: 10px;
}

.infoview input,
.infoview select,
.infoview textarea {
  color: #ffffff;
  background-color: rgba(32, 160, 255, 0.2);
  border: 1px solid #e4eaec;
  font-size: 14px;
}

.infoview > div {
  margin-top: 5px;
}

.resultview {
  max-width: 500px;
  display: flex;
  text-align: center;
}

.el-input {
  width: 250px;
}

.el-table {
  text-align: center;
}
</style>
